#include "utils/Logger.h"
#include <QDateTime>
#include <QDebug>

Logger::Logger() {}
Logger::~Logger()
{
    if (m_logFile.isOpen()) {
        m_logFile.close();
    }
}

Logger& Logger::instance()
{
    static Logger instance;
    return instance;
}

void Logger::log(LogLevel level, const QString &message)
{
    if (level < m_logLevel) return;
    
    QString timestamp = QDateTime::currentDateTime().toString("yyyy-MM-dd hh:mm:ss");
    QString levelStr = levelToString(level);
    QString logMessage = QString("[%1] [%2] %3").arg(timestamp).arg(levelStr).arg(message);
    
    // 输出到控制台
    qDebug() << logMessage;
    
    // 输出到文件
    if (m_logFile.isOpen()) {
        m_stream << logMessage << Qt::endl;
        m_stream.flush();
    }
}

void Logger::setLogFile(const QString &filePath)
{
    if (m_logFile.isOpen()) {
        m_logFile.close();
    }
    
    m_logFile.setFileName(filePath);
    if (m_logFile.open(QIODevice::WriteOnly | QIODevice::Append | QIODevice::Text)) {
        m_stream.setDevice(&m_logFile);
    }
}

QString Logger::levelToString(LogLevel level)
{
    switch (level) {
        case Debug: return "DEBUG";
        case Info: return "INFO";
        case Warning: return "WARN";
        case Error: return "ERROR";
        case Fatal: return "FATAL";
        default: return "UNKNOWN";
    }
}